var _100SUSTAIN = 1007878246;

function upgradeSecurityIdAndDisplayInfoSecurityIdentifier(portfolioDetails, companySearch) {
	var operationsCounter = 0;
	var operationsManager = portfolioDetails.initializeUnorderedBulkOp();
	
	portfolioDetails.find().forEach(d => {
            var securityId = "-" + d.SecurityId;                       
            var clientIdentifier = d.DisplayInfo.SecurityIdentifier;
            var isClientIdentifierAnOldCIQID = clientIdentifier.substring(0, 2).toUpperCase() == "IQ" && 
                                                clientIdentifier.substring(2) == (parseInt(d.MatchedInfo.CapitalIQId) - _100SUSTAIN).toString();
            
            var companyIdentifier = null; 
            
            if (isClientIdentifierAnOldCIQID) {
                clientIdentifier = d.MatchedInfo.CapitalIQId;
            }
            else {                
                companyIdentifier = companySearch.findOne({CompanyId: d.CompanyId, IdentifierValue: clientIdentifier.toLowerCase()});
            }
                                   
            if (companyIdentifier) { 
                securityId = companyIdentifier.SecurityId;                
            } 
            else {
                companyIdentifier = companySearch.findOne({CompanyId: d.CompanyId});
                
                if (companyIdentifier) { 
                    securityId = companyIdentifier.MainSecurityId;                
                } 
            }
            
	    operationsManager.find({_id: d._id}).updateOne({ $set: { SecurityId: securityId, "DisplayInfo.SecurityIdentifier": clientIdentifier }});
	    
	    if (++operationsCounter == 1000) { 		
                operationsManager.execute();
                
                operationsManager = portfolioDetails.initializeUnorderedBulkOp();
                
                operationsCounter = 0;
            }
	});
	
	operationsManager.execute();
}

var clientPlatformDB = db.getSiblingDB("ClientPlatform");

var companySearchCollection = db.getSiblingDB(clientPlatformDB.getCollection("ConnectionStrings").findOne().CompanySearchDW.split("/").slice(-1)).CompanySearch;

upgradeSecurityIdAndDisplayInfoSecurityIdentifier(clientPlatformDB.PortfolioDetails, companySearchCollection);

upgradeSecurityIdAndDisplayInfoSecurityIdentifier(clientPlatformDB.PortfolioMatches, companySearchCollection);


